import Vue from "vue";
import ptmsgVue from "./main.vue";

let MessageConstructor = Vue.extend(ptmsgVue);
let instance = "";
const MessageBox = function(option = {}) {
  // 如果存在实例，则不进行后续操作
  if (instance) {
    return;
  }

  // 如果option为string，则转换成object类型
  if (typeof option === "string") {
    option = { message: option };
  }

  // 创建实例
  instance = new MessageConstructor({
    data: option
  });

  // 关闭之后重置实例为空
  instance.onClose = function() {
    instance = "";
  };

  instance.$mount();
  document.body.appendChild(instance.$el);
  return instance;
};

["success", "warning", "info", "error"].forEach(type => {
  MessageBox[type] = options => {
    if (typeof options === "string") {
      options = {
        message: options
      };
    }
    options.type = type;
    return MessageBox(options);
  };
});

export default MessageBox;
